package my.suveng.util.validate;

import cn.hutool.core.lang.caller.CallerUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import my.suveng.model.common.interfaces.define.SpringUtil;
import my.suveng.model.common.interfaces.response.IMessage;
import my.suveng.model.common.response.Message;
import my.suveng.util.log.PlusLogFactoryHutool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 参数校验
 * @author suwenguang
 **/
@Component
@SpringUtil
public class ValidateUtil {
    @Autowired
    Validator validator;

    //hutool日志
    private static final Log log = LogFactory.setCurrentLogFactory(new PlusLogFactoryHutool()).getLog(CallerUtil.getCaller().getName());

    /**
     * 参数校验,有返回
     * @author suwenguang
     */
    <T> IMessage<T> validate(T object) {
        Set<ConstraintViolation<T>> validate = validator.validate(object);
        if (validate.size() > 0) {
            for (ConstraintViolation<T> e : validate) {
                String msg = "参数校验不通过:" + e.getPropertyPath() + e.getMessage();
                log.error(msg);
                return Message.error(msg);
            }
        }

        return Message.successWithData(object);
    }

}
